/*
 * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package top.continew.admin.auth.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import top.continew.admin.auth.model.resp.WechatUserInfo;
import top.continew.admin.system.service.OptionService;
import top.continew.starter.core.exception.BadRequestException;

/**
 * 微信API服务
 *
 * @author Charles7c
 * @since 2024/12/22
 */
@Slf4j
@Service
public class WechatApiService {

    @Value("${weChat.miniProgram.enabled}") // 正确：使用双引号
    private boolean enabled;

    @Value("${weChat.miniProgram.appId}")
    private String appId;

    @Value("${weChat.miniProgram.appSecret}")
    private String appSecret;

    /**
     * 微信小程序code2Session接口URL
     */
    private static final String CODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 通过授权码获取用户信息
     *
     * @param code          授权码
     * @return 微信用户信息
     */
    public WechatUserInfo getUserInfo(String code) {
        // 获取微信小程序配置
        if (!enabled) {
            throw new BadRequestException("微信小程序登录未启用");
        }
        if (StrUtil.isBlank(appId) || StrUtil.isBlank(appSecret)) {
            throw new BadRequestException("微信小程序AppID或AppSecret配置错误");
        }
        
        // Validate input parameters
        if (StrUtil.isBlank(code)) {
            throw new BadRequestException("授权码不能为空");
        }
        
        // 调用微信code2session接口
        String code2SessionJson = code2Session(appId, appSecret, code);
        JSONObject code2SessionObj = JSONUtil.parseObj(code2SessionJson);
        log.info("code2SessionJson:{}", code2SessionJson);
        return code2SessionObj.toBean(WechatUserInfo.class);
    }

    /**
     * 调用微信code2session接口
     *
     * @param appId     小程序AppID
     * @param appSecret 小程序AppSecret
     * @param code      授权码
     * @return 响应结果
     */
    private String code2Session(String appId, String appSecret, String code) {
        String url = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                CODE_TO_SESSION_URL, appId, appSecret, code);

        try {
            return HttpUtil.get(url, 5000);
        } catch (Exception e) {
            log.error("调用微信code2session接口失败", e);
            throw new BadRequestException("微信服务暂时不可用，请稍后再试");
        }
    }
}